package com.study.kafka.producer;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Resource;
import org.apache.kafka.common.PartitionInfo;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;

/**
 * @description: 消息生产者
 * @author: liujiawei
 * @create: 2019-04-18 14:10
 **/
@Component
@EnableScheduling
public class Producer {
    @Resource
    private KafkaTemplate kafkaTemplate;

    private AtomicInteger index = new AtomicInteger(0);

    @Scheduled(cron = "0/1 * * * * ?")
    public void send() {
        // 获取topic hello的分区信息
        List<PartitionInfo> partitionInfos = kafkaTemplate.partitionsFor("hello");
        System.out.println("topic[hello]的分区数量：" + partitionInfos.size());
        String message = "msgId:%s 来自producer的消息";
        message = String.format(message, UUID.randomUUID().toString());
        ListenableFuture future = kafkaTemplate.send("hello", partitionInfos.get(index.getAndAdd(1) % partitionInfos.size()).partition(), null, message);
        future.addCallback(o -> {
            System.out.println("消息发送成功");
        }, throwable -> {
            System.out.println("消息发送失败");

        });
    }
}
